#include "strategy.h"
#include <regex>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <sstream>
using namespace std;
TXTStrategy* TXTStrategy::inst = NULL;
XMLStrategy* XMLStrategy::inst = NULL;
LocalStrategy* LocalStrategy::inst = NULL;
bool
is_contained(vector<string> &dict,string str){
  for(auto pattern:dict){
    if(pattern == str)
      return true;
  }
  return false;
}
vector<string>
spilt(string str){
  regex reg(",|\\.");
  string target(" ");
  string tmp = std::regex_replace(str,reg,target);
  char *strc = new char[strlen(tmp.c_str())+1];
  strcpy(strc,tmp.c_str());
  vector<string>result;
  char *tmp_strc = strtok(strc," ");
  while(tmp_strc != NULL){
    result.push_back(string(tmp_strc));
    tmp_strc = strtok(NULL," ");
  }
  delete[] strc;
  vector<string>::iterator iter;
  for(iter = result.begin();iter != result.end(); ){
    if((*iter) == " ")
      iter = result.erase(iter);
    else 
      iter++;
  }
  return result;
}
string
XMLStrategy::filt(string context){
  regex reg("<\\w+>|</\\w+>");
  string target(" ");
  return regex_replace(context,reg,target);
}
vector<std::string>
LocalStrategy::check(string context){
  vector<string> strs = spilt(context);
  ifstream in;
  in.open(lexicon.data(),ios::in);
  if(!in.is_open()){
    cerr << "Error:file " << lexicon << " can't be open!" << endl;
    exit(EXIT_FAILURE);
  }
  string buffer;
  vector<string>dict;
  while(getline(in,buffer)){
    std::string tmp = buffer;
    if(tmp.empty())
      continue;
    tmp.erase(0,tmp.find_first_not_of(" "));
    tmp.erase(tmp.find_last_not_of("\n\r\t")+1);
    tmp.erase(tmp.find_last_not_of(" ")+1);
    dict.push_back(tmp);
  }
  in.close();
  vector<string> result;
  for(string str:strs){
    if(str.empty())
      continue;
    str.erase(0,str.find_first_not_of(" "));
    str.erase(str.find_last_not_of(" ")+1);
    str.erase(str.find_last_not_of("\n\r\t")+1);
    if(!is_contained(dict,str))
     result.push_back(str);
  }
  return result;
}
